using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.Modeling;
using Microsoft.VisualStudio.Modeling.Diagrams;

namespace Microsoft.Modeling.StoryboardDesigner
{
    public partial class StoryboardDesignerDomainModel
    {
        /// <summary>
        /// Register the rules related to highlighting shapes based
        /// on the "LinkedFile" property.
        /// </summary>
        /// <returns></returns>
        private void AddLinkedFileRules(List<System.Type> types)
        {
            // Rules to highlight shape when the "Linked File" property
            // is set.
            types.Add(typeof(LinkedFilePropertyChangedRule));
            types.Add(typeof(HighlightLinkedElementOnShapeCreatedAddRule));
        }
    }

    /// <summary>
    /// </summary>
    [RuleOn(typeof(StoryboardElement), FireTime = TimeToFire.TopLevelCommit)]
    public sealed class LinkedFilePropertyChangedRule : Microsoft.VisualStudio.Modeling.ChangeRule
    {
        public override void ElementPropertyChanged(ElementPropertyChangedEventArgs e)
        {
            StoryboardElement storyboardElement = e.ModelElement as StoryboardElement;

            if(storyboardElement == null)
            {
                return;
            }

            // Property of storyboard element has been changed.
            // Only interested in "Linked File"
            if(e.DomainProperty.Id != StoryboardElement.LinkedFileDomainPropertyId)
            {
                return;
            }

            // Hightlight the shape representing the element
            IList<PresentationElement> pels = PresentationViewsSubject.GetPresentation(storyboardElement);

            foreach(PresentationElement pel in pels)
            {
                IStoryboardPel storyboardPel = pel as IStoryboardPel;

                if(storyboardPel != null)
                {
                    storyboardPel.UpdateExternalLinkHighlighting();
                }
            }
        }
    }

    [RuleOn(typeof(PresentationViewsSubject), FireTime = TimeToFire.TopLevelCommit)]
    public sealed class HighlightLinkedElementOnShapeCreatedAddRule : AddRule
    {
        public override void ElementAdded(ElementAddedEventArgs e)
        {
            PresentationViewsSubject pvs = e.ModelElement as PresentationViewsSubject;

            if(pvs == null)
            {
                return;
            }

            // A new link between a presentation and a subject has been
            // created. However, we are only interested in links to shapes
            // that represent storyboard elements.

            IStoryboardPel storyboardPel = pvs.Presentation as IStoryboardPel;

            if(storyboardPel != null)
            {
                storyboardPel.UpdateExternalLinkHighlighting();
            }
        }
    }
}